package com.yhm.NIO.simpleNIO处理完毕一个客户端的发送数据后才能接收第二个客户端的连接;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class YhmNIOServer {


  public static void main(String[] args) {

    try {
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.bind(new InetSocketAddress(8080));


      while (true) {
        SocketChannel socketChannel = serverSocketChannel.accept();
        if( socketChannel==null )continue;
        System.out.println("服务端接收到客户端连接,RemoteAddress=" + socketChannel.getRemoteAddress() + ",Blocking=" + socketChannel.isBlocking());


        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        while (socketChannel.isOpen() && (socketChannel.read(readBuffer) != -1)) {
          if( readBuffer.position()>0 )break;
        }

        //接收数据
        readBuffer.flip();
        byte[] receiveBytes = new byte[readBuffer.limit()];
        readBuffer.get(receiveBytes);
        System.out.println("接收到客户端数据" + new String(receiveBytes));

        //发送数据
        ByteBuffer sendBuffer = ByteBuffer.wrap(("服务端返回" + Math.random() + "数据").getBytes());
        while (socketChannel.isOpen() && (socketChannel.write(sendBuffer) != -1)) {
          if (sendBuffer.position() > 0) {
            break;
          }
        }
        socketChannel.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }


  }


}
